package com.xianbeiying.app.ckgl.photo.activity;

import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.os.Environment;
import android.support.v7.widget.ListPopupWindow;
import android.view.Gravity;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.fastjson.JSON;
import com.lidroid.xutils.ViewUtils;
import com.lidroid.xutils.util.LogUtils;
import com.lidroid.xutils.view.annotation.ViewInject;
import com.xianbeiying.app.ckgl.MyApplication;
import com.xianbeiying.app.ckgl.R;
import com.xianbeiying.app.ckgl.activity.BaseActivity;
import com.xianbeiying.app.ckgl.bean.ImageBean;
import com.xianbeiying.app.ckgl.http.HttpCallBackUtil;
import com.xianbeiying.app.ckgl.model.ImageModel;
import com.xianbeiying.app.ckgl.photo.adapter.PhotoMultiGridAdapter;
import com.xianbeiying.app.ckgl.photo.entity.Photo;
import com.xianbeiying.app.ckgl.photo.entity.PhotoDirectory;
import com.xianbeiying.app.ckgl.photo.event.OnItemClickListener;
import com.xianbeiying.app.ckgl.photo.fragment.ImagePagerFragment;
import com.xianbeiying.app.ckgl.photo.fragment.PhotoPickerFragment;
import com.xianbeiying.app.ckgl.photo.util.ImageCaptureManager;
import com.xianbeiying.app.ckgl.util.BitmapAndStringUtils;
import com.xianbeiying.app.ckgl.util.SharedPreferencesUtils;
import com.xianbeiying.app.ckgl.util.StringUtil;
import com.xianbeiying.app.ckgl.util.ToastUtil;

import java.io.IOException;
import java.util.ArrayList;

import static android.widget.Toast.LENGTH_LONG;

/**
 * 图片选择
 */
public class PhotoPickerActivity extends BaseActivity implements HttpCallBackUtil{
    public static final int INDEX_ALL_PHOTOS = 0;
    private ImageCaptureManager captureManager;
    private PhotoPickerFragment pickerFragment;
    private ImagePagerFragment imagePagerFragment;
    private ImagePagerFragment selectedPagerFragment;
    public final static String EXTRA_MAX_COUNT = "MAX_COUNT";
    public final static String FATHER = "FATHER";
    public final static String FATHER_SUN = "FATHER_SUN";
    public final static String EXTRA_SHOW_CAMERA = "SHOW_CAMERA";
    public final static String EXTRA_SHOW_GIF = "SHOW_GIF";
    public final static String EXTRA_MULTI_CHOOSE = "MULTI_CHOOSE";
    public final static String KEY_SELECTED_PHOTOS = "SELECTED_PHOTOS";
    //完成
    private Button btnDoneItem;
    public final static int DEFAULT_MAX_COUNT = 9;

    private int maxCount = DEFAULT_MAX_COUNT;
    private boolean showGif = false;
    private boolean multiChoose = false;
    private PhotoMultiGridAdapter multiGridAdapter;
    //标题
    @ViewInject(R.id.tv_title)
    private TextView tv_title;
    //返回
    @ViewInject(R.id.ly_title_left)
    private LinearLayout ly_title_left;
    //右边
    @ViewInject(R.id.iv_right)
    private ImageView iv_right;
    @ViewInject(R.id.ly_title_right)
    private LinearLayout ly_title_right;
    private int father_sun,father;
    //传过来的东西
    private String title;
    private ImageModel imageModel;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        imageModel=new ImageModel(this);
        imageModel.addResponseListener(this);
        boolean showGif = getIntent().getBooleanExtra(EXTRA_SHOW_GIF, false);
        multiChoose = getIntent().getBooleanExtra(EXTRA_MULTI_CHOOSE, false);
        title=getIntent().getStringExtra("fragment");
        setShowGif(showGif);
        setContentView(R.layout.activity_photo_picker);
        ViewUtils.inject(this);
        init();
        captureManager = new ImageCaptureManager(getActivity());
        maxCount = getIntent().getIntExtra(EXTRA_MAX_COUNT, DEFAULT_MAX_COUNT);
        father_sun = getIntent().getIntExtra(FATHER_SUN, -1);
        father = getIntent().getIntExtra(FATHER, -1);
        btnDoneItem = (Button) findViewById(R.id.done);
        btnDoneItem.setText(getString(R.string.done_with_count, 0, maxCount));
        btnDoneItem.setEnabled(false);
//        为确定
        btnDoneItem.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                ArrayList<String> selectedPhotos = pickerFragment.getPhotoGridAdapter().getSelectedPhotoPaths();
                if(title!=null&&title.equals("MyFragment")){
                    //图片上传
                    Bitmap bitmap = StringUtil.getLoacalBitmap(selectedPhotos.get(0));
                    if (selectedPhotos.get(0).contains(".png")) {
                        imageModel.ImageLogin(SharedPreferencesUtils.getStringDate("username"), MyApplication.loginBean.getUSERID(), "png;" + BitmapAndStringUtils.convertIconToString(bitmap), true);
                    }
                    if (selectedPhotos.get(0).contains(".jpg")){
                        imageModel.ImageLogin(SharedPreferencesUtils.getStringDate("username"), MyApplication.loginBean.getUSERID(), "jpg;" + BitmapAndStringUtils.convertIconToString(bitmap), true);
                    }
                }else{
                    Intent intent = new Intent();
                    intent.putStringArrayListExtra(KEY_SELECTED_PHOTOS, selectedPhotos);
                    intent.putExtra(FATHER_SUN, father_sun);
                    intent.putExtra(FATHER, father);
                    setResult(RESULT_OK, intent);
                    finish();
                }

            }
        });

        final Button btSwitchDirectory = (Button) findViewById(R.id.button);
        pickerFragment = (PhotoPickerFragment) getSupportFragmentManager().findFragmentById(R.id.photoPickerFragment);
        final ListPopupWindow listPopupWindow = new ListPopupWindow(getActivity());
        listPopupWindow.setWidth(ListPopupWindow.MATCH_PARENT);
        listPopupWindow.setAnchorView(findViewById(R.id.ll_control));
        listPopupWindow.setAdapter(pickerFragment.getListAdapter());
        listPopupWindow.setModal(true);
        listPopupWindow.setDropDownGravity(Gravity.BOTTOM);
        listPopupWindow.setAnimationStyle(R.style.Animation_AppCompat_DropDownUp);

        listPopupWindow.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                LogUtils.e("-------2222");
                listPopupWindow.dismiss();
                PhotoDirectory directory = pickerFragment.getDirectories().get(position);
                btSwitchDirectory.setText(directory.getName());
                pickerFragment.getPhotoGridAdapter().setCurrentDirectoryIndex(position);
                pickerFragment.getPhotoGridAdapter().notifyDataSetChanged();
            }
        });

        btSwitchDirectory.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                LogUtils.e("-------1111");
                if (listPopupWindow.isShowing()) {
                    listPopupWindow.dismiss();
                } else if (!getActivity().isFinishing()) {
                    listPopupWindow.setHeight(Math.round(pickerFragment.getView().getHeight() * 0.8f));
                    listPopupWindow.show();
                }

            }
        });
        multiGridAdapter = pickerFragment.getPhotoGridAdapter();
        multiGridAdapter.setOnItemClickListener(new OnItemClickListener() {
            @Override
            public void onItemClick(int position, Photo photo, int selectedItemCount, int selectTimes) {
                LogUtils.e("-------3333");
                if (multiChoose) {
                    if (photo.getSelectedTimes() > 0) {
                        if (selectedItemCount >= maxCount) {
                            multiGridAdapter.del(photo);
                            multiGridAdapter.notifyItemChanged(position);
                        } else {
                            multiGridAdapter.add(photo);
                            multiGridAdapter.notifyItemChanged(position);
                        }
                    } else {
                        if (selectedItemCount >= maxCount) {
                            Toast.makeText(getActivity(), getString(R.string.over_max_count_tips, maxCount),
                                    LENGTH_LONG).show();
                        } else {
                            multiGridAdapter.add(photo);
                            multiGridAdapter.notifyItemChanged(position);
                        }
                    }
                } else {
                    if (maxCount <= 1) {
                        if (photo.getSelectedTimes() > 0) {
                            multiGridAdapter.del(0);
                            multiGridAdapter.notifyItemChanged(position);
                        } else {
                            multiGridAdapter.clearSelection();
                            multiGridAdapter.add(photo);
                            multiGridAdapter.notifyDataSetChanged();
                        }
                    } else {
                        if (photo.getSelectedTimes() > 0) {
                            multiGridAdapter.del(photo);
                            multiGridAdapter.notifyItemChanged(position);
                        } else {
                            if (selectedItemCount >= maxCount) {
                                Toast.makeText(getActivity(), getString(R.string.over_max_count_tips, maxCount),
                                        LENGTH_LONG).show();
                            } else {
                                multiGridAdapter.add(photo);
                                multiGridAdapter.notifyItemChanged(position);
                            }
                        }
                    }
                }
                refreshDoneBtn();

            }
        });
    }


    private void init() {
        tv_title.setText("图片选择");
        iv_right.setVisibility(View.VISIBLE);
        iv_right.setImageResource(R.mipmap.camera);
        //返回
        ly_title_left.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
        //拍照
        ly_title_right.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                try {
                    Intent intent = captureManager.dispatchTakePictureIntent();
                    startActivityForResult(intent, ImageCaptureManager.REQUEST_TAKE_PHOTO);
                } catch (IOException e) {
                    e.printStackTrace();
                }

            }
        });
    }
    private void refreshDoneBtn() {

        int selectedCount = multiGridAdapter.getSelectedItemCount();
        btnDoneItem.setEnabled(selectedCount > 0);
        btnDoneItem.setText(getString(R.string.done_with_count, selectedCount, maxCount));
    }

    @Override
    public void onBackPressed() {
        if (imagePagerFragment != null && imagePagerFragment.isVisible()) {
            imagePagerFragment.runExitAnimation(new Runnable() {
                public void run() {
                    if (getSupportFragmentManager().getBackStackEntryCount() > 0) {
                        getSupportFragmentManager().popBackStack();
                    }
                }
            });
        } else {
            super.onBackPressed();
        }
    }


    public void addImagePagerFragment(ImagePagerFragment imagePagerFragment, boolean isSelected) {
        if (isSelected) {
            this.selectedPagerFragment = imagePagerFragment;
            if (this.imagePagerFragment != null && this.imagePagerFragment.isVisible()) {
                if (getSupportFragmentManager().getBackStackEntryCount() > 0) {
                    getSupportFragmentManager().popBackStack();
                }
            }
        } else {
            this.imagePagerFragment = imagePagerFragment;
            if (this.selectedPagerFragment != null && this.selectedPagerFragment.isVisible()) {
                if (getSupportFragmentManager().getBackStackEntryCount() > 0) {
                    getSupportFragmentManager().popBackStack();
                }
            }

        }
        getSupportFragmentManager()
                .beginTransaction()
                .replace(R.id.container, imagePagerFragment)
                .addToBackStack(null)
                .commit();
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (requestCode == ImageCaptureManager.REQUEST_TAKE_PHOTO && resultCode == RESULT_OK) {
            captureManager.galleryAddPic(null);
//            MediaStoreHelper.setIsBlock(true);
            if (multiGridAdapter.getPhotoDirectories().size() > 0) {
                String path = captureManager.getCurrentPhotoPath();
                PhotoDirectory directory = multiGridAdapter.getPhotoDirectories().get(INDEX_ALL_PHOTOS);
                Photo newPhoto = new Photo(path.hashCode(), path);
                directory.getPhotos().add(INDEX_ALL_PHOTOS, newPhoto);
                directory.setCoverPath(path);

                for (PhotoDirectory item : multiGridAdapter.getPhotoDirectories()) {
                    if (item.getName().equals(Environment.DIRECTORY_PICTURES)) {
                        item.getPhotos().add(INDEX_ALL_PHOTOS, newPhoto);
                        item.setCoverPath(path);
                        break;
                    }
                }

                if (multiChoose) {
                    if (multiGridAdapter.getSelectedItemCount() >= maxCount) {
                        Toast.makeText(getActivity(), getString(R.string.over_max_count_tips, maxCount),
                                LENGTH_LONG).show();
                    } else {
                        multiGridAdapter.add(newPhoto);
                    }
                } else {
                    if (maxCount <= 1) {
                        multiGridAdapter.clearSelection();
                        multiGridAdapter.add(newPhoto);
                    } else {
                        if (multiGridAdapter.getSelectedItemCount() >= maxCount) {
                            Toast.makeText(getActivity(), getString(R.string.over_max_count_tips, maxCount),
                                    LENGTH_LONG).show();
                        } else {
                            multiGridAdapter.add(newPhoto);
                        }
                    }
                }
                refreshDoneBtn();
                multiGridAdapter.notifyDataSetChanged();
                pickerFragment.getListAdapter().notifyDataSetChanged();
            }
        }
    }

    public PhotoPickerActivity getActivity() {
        return this;
    }

    public boolean isShowGif() {
        return showGif;
    }

    public void setShowGif(boolean showGif) {
        this.showGif = showGif;
    }

    public boolean isMultiChoose() {
        return multiChoose;
    }

    public void setMultiChoose(boolean multiChoose) {
        this.multiChoose = multiChoose;
    }
    private ImageBean imageBean;
    @Override
    public void onCallBackData(String url, Object content) {
        if (url.equals("图片")){
            LogUtils.e(content.toString() + "==============");
            imageBean = JSON.parseObject(content.toString(), ImageBean.class);
            if (imageBean.isR()) {
                ToastUtil.showInfo(MyApplication.getInstance(), "上传成功");
                LogUtils.e(imageBean.getUserurl() + "==============");
                if (MyApplication.loginBean != null) {
                    MyApplication.loginBean.setUSERURL(imageBean.getUserurl());
                }
                finish();
            } else {
                ToastUtil.showInfo(MyApplication.getInstance(), "上传失败");
            }
        }
    }
}
